var util = require('../../utils/util.js')
const db = wx.cloud.database()
Page({
  data: {
    calendar: [],
    width: 0,
    currentIndex: 0,
    roomID: "",
    selectDate: "",
    records:[]
  },

  onLoad: function(options) {
    var roomID = options.roomID
    var date1 = new Date()
    var weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    var calendar = []
    for (var i = 0; i < 7; i++) {
      var myDate = {}
      var date2 = new Date(date1);
      date2.setDate(date1.getDate() + i);
      myDate.date = util.formatTime(date2)
      myDate.week = '星期'+weeks_ch[date2.getDay()]
      calendar.push(myDate)
    }
    this.setData({
      width: 185 * 7, calendar: calendar, roomID: roomID, selectDate: calendar[0].date
    })
  },

  getRecords()
  {
    var roomID = this.data.roomID
    var selectDate = this.data.selectDate
    db.collection('order').where({
      roomID: roomID,
      selectDate: selectDate
    }).get().then(res => {
      this.setData({ records: res.data })
    })
  },

  onShow:function(event)
  {
    this.getRecords()
  },

  select: function(event) {
    this.setData({
      currentIndex: event.currentTarget.dataset.index,
      selectDate: event.currentTarget.dataset.date
    })
    this.getRecords()
  },

  gotoAppointment: function(event) {
    var phone = wx.getStorageSync('phone');
    if (phone == "") {
      wx.navigateTo({
        url: '../login/login'
      })
    } else {
      console.log(phone)
      db.collection('contact').where({
        celphone: parseInt(phone)
      }).get().then(res => {
        console.log(res)
        if(res.data.length==1)
        {
          wx.setStorageSync('user', res.data[0]);
          var roomID = this.data.roomID
          var selectDate = this.data.selectDate
          wx.navigateTo({
            url: '../meetingform/meetingform?roomID=' + roomID + '&selectDate=' + selectDate
          })
        }
        else
        {
          wx.showToast({
            title: '您没有权限预约',
            icon: 'success',
            duration: 2000
          })
        }
      })
    }
  },

  deleteRecord:function(event)
  {
    var id=event.currentTarget.dataset.index
    var records=this.data.records
    var phone = wx.getStorageSync('phone');
    if (phone == records[id].adminphone || phone == records[id].celphone) {
      wx.cloud.callFunction({
        name: 'DeleteOrder',
        data: {
          id: records[id]._id,
        }
      }).then(res => {
        records.splice(id, 1)
        this.setData({
          records: records
        })
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        })
      }).catch(err => {
      })
    }
    else
    {
      wx.showToast({
        title: '您没有权限删除该预约',
        icon: 'success',
        duration: 2000
      })
    }
  },
})